<template>
    <div>
        <van-nav-bar title="返回" left-text="返回" left-arrow @click-left="$router.back()" />
        <form action="/">
            <van-search v-model="value" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="$router.back()" />
        </form>
        <div class="search-List">
            <div class="serch-item" v-for="item in searchList" style="width: 175px"
                @click="$router.push({ name: 'detiall', params: { id: item.id } })">
                <img :src="item.list_pic_url" alt="" style="width: 175px; height: 175px; background-color: #fff;">
                <div class="title">
                    {{ item.name }}
                </div>
                <div class="price" style="color: #9e4242; margin: 10px 0;">
                    ￥ {{ item.retail_price }}
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { getSearchClickApi, getSearchClickListApi } from '@/api/search'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router';
const value = ref<string>()
const $router = useRouter()
// 准备一个变量, 表示当前列表页关键字
const keyword = ref<string>('电脑')
// 获取数据传入的参数，用来排序
const order = ref<'desc' | 'asc'>('desc')
// 页面渲染的数据
const searchList = ref<SearchNs.ISearchClickListItem[]>([])
// 点击搜索事件
const onSearch = (word: string, id: string) => {
    const res = getSearchClickApi(word, id)
    // 跳转路由
    $router.push('/list')
}
const getKeyword = () => {
    const list = JSON.parse(window.localStorage.getItem('history') || '[]')
    // 当 list[0] 有内容的时候, 才给 keyword 赋值
    if (list[0])
        keyword.value = list[0]

}
// 列表页面数据
const getSearchListHanlder = async () => {
    const res = await getSearchClickListApi(keyword.value, order.value)
    searchList.value = res.keywords

}
onMounted(() => {
    getKeyword()
    getSearchListHanlder()
})
</script>

<style scoped lang="scss">
.search-List {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 8px;

    .title {
        white-space: nowrap;
        width: 80%;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
</style>